package com.dji.custom.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dji.custom.dao.IExpandWaylineFileMapper;
import com.dji.custom.model.dto.MultipartFileDto;
import com.dji.custom.model.entity.ExpandWaylineFileEntity;
import com.dji.custom.service.IExpandWaylineFileService;
import com.dji.custom.util.CustomUtil;
import com.dji.sample.wayline.model.dto.KmzFileProperties;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 航线拓展Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-31
 */
@Service
public class ExpandWaylineFileServiceImpl implements IExpandWaylineFileService
{
    @Autowired
    private IExpandWaylineFileMapper expandWaylineFileMapper;

    private static final String minioUrl = "http://47.94.150.134:9000/cloud-bucket/";


    @Override
    public int insertExpandWaylineFileCustom(String waylineId, String objectKey) {
        ExpandWaylineFileEntity expandWaylineFileInsert = new ExpandWaylineFileEntity();
        expandWaylineFileInsert.setWaylineId(waylineId);
        try {
            // 根据文件地址获取file流
            String filePath = minioUrl + objectKey;
            expandWaylineFileInsert.setWaylineUrl(filePath);
            File file = CustomUtil.urlToFile(new URL(filePath));
            // 创建一个文件输入流，将File对象作为参数传入
            FileInputStream inputStream = new FileInputStream(file);
            // 创建一个MockMultipartFile对象，将文件名、文件字节流、文件类型作为参数传入
            MultipartFile multipartFile = new MultipartFileDto(file.getName(), inputStream);
            List<Map> nodeList = new ArrayList<>();
            validKmzFileNew(multipartFile, nodeList, expandWaylineFileInsert);
        }catch (Exception e){
            e.printStackTrace();
        }
        return expandWaylineFileMapper.insert(expandWaylineFileInsert);
    }

    @Override
    public int deleteExpandWaylineFileCustom(String waylineId) {
        return expandWaylineFileMapper.delete(new LambdaUpdateWrapper<ExpandWaylineFileEntity>()
                .eq(ExpandWaylineFileEntity::getWaylineId, waylineId));
    }

    private static void validKmzFileNew(MultipartFile file, List<Map> nodeList, ExpandWaylineFileEntity expandWaylineFileInsert) {
        String distance = "";
        String executeHeight = "";
        String speed = "";
        try (ZipInputStream unzipFile = new ZipInputStream(file.getInputStream(), StandardCharsets.UTF_8)) {

            ZipEntry nextEntry = unzipFile.getNextEntry();
            while (Objects.nonNull(nextEntry)) {
                //boolean isWaylines = (KmzFileProperties.FILE_DIR_FIRST + File.separator + KmzFileProperties.FILE_DIR_SECOND_WAYLINES).equals(nextEntry.getName());
                boolean isWaylines = (KmzFileProperties.FILE_DIR_FIRST + "/" + KmzFileProperties.FILE_DIR_SECOND_WAYLINES).equals(nextEntry.getName());
                if (!isWaylines) {
                    nextEntry = unzipFile.getNextEntry();
                    continue;
                }
                // 获取经纬度子节点集合
                SAXReader reader = new SAXReader();
                Document document = reader.read(unzipFile);
                distance = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + "distance");
                executeHeight = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + "executeHeight");
            }

        } catch (IOException | DocumentException e) {
            //e.printStackTrace();
        }
        try (ZipInputStream unzipFile = new ZipInputStream(file.getInputStream(), StandardCharsets.UTF_8)) {

            ZipEntry nextEntry = unzipFile.getNextEntry();
            while (Objects.nonNull(nextEntry)) {
                //boolean isWaylines = (KmzFileProperties.FILE_DIR_FIRST + File.separator + KmzFileProperties.FILE_DIR_SECOND_TEMPLATE).equals(nextEntry.getName());
                boolean isWaylines = (KmzFileProperties.FILE_DIR_FIRST + "/" + KmzFileProperties.FILE_DIR_SECOND_TEMPLATE).equals(nextEntry.getName());
                if (!isWaylines) {
                    nextEntry = unzipFile.getNextEntry();
                    continue;
                }
                // 获取经纬度子节点集合
                SAXReader reader = new SAXReader();
                Document document = reader.read(unzipFile);
                Element root = document.getRootElement();//获取kml文件的根结点
                CustomUtil.listNodes(root, nodeList);
                if (!StandardCharsets.UTF_8.name().equals(document.getXMLEncoding())) {
                    throw new RuntimeException("The file encoding format is incorrect.");
                }

                Node droneNode = document.selectSingleNode("//" + KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_DRONE_INFO);
                Node payloadNode = document.selectSingleNode("//" + KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_PAYLOAD_INFO);
                //String distance = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_DISTANCE);
                String autoFlightSpeed = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + "autoFlightSpeed");
                //String executeHeight = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_HEIGHT);
                if (Objects.isNull(droneNode) || Objects.isNull(payloadNode)) {
                    throw new RuntimeException("The file format is incorrect.");
                }
                speed = autoFlightSpeed;

                String type = droneNode.valueOf(KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_DRONE_ENUM_VALUE);
                String subType = droneNode.valueOf(KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_DRONE_SUB_ENUM_VALUE);
                String payloadType = payloadNode.valueOf(KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_PAYLOAD_ENUM_VALUE);
                String payloadSubType = payloadNode.valueOf(KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_PAYLOAD_SUB_ENUM_VALUE);
                String templateType = document.valueOf("//" + KmzFileProperties.TAG_WPML_PREFIX + KmzFileProperties.TAG_TEMPLATE_TYPE);

                if (!StringUtils.hasText(type) || !StringUtils.hasText(subType) ||
                        !StringUtils.hasText(payloadSubType) || !StringUtils.hasText(payloadType) ||
                        !StringUtils.hasText(templateType)) {
                    throw new RuntimeException("The file format is incorrect.");
                }
            }

        } catch (IOException | DocumentException e) {
           // e.printStackTrace();
        }
        distance = org.apache.commons.lang3.StringUtils.isEmpty(distance)? "0" : distance;
        BigDecimal distanceBig = new BigDecimal(distance);
        distanceBig = distanceBig.divide(BigDecimal.valueOf(1000)).setScale(2, BigDecimal.ROUND_DOWN);
        executeHeight = org.apache.commons.lang3.StringUtils.isEmpty(executeHeight)? "0" : executeHeight;
        expandWaylineFileInsert.setWaylineDetail(nodeList.toString());
        expandWaylineFileInsert.setDistance(distanceBig);
        expandWaylineFileInsert.setHeight(new BigDecimal(executeHeight));
        expandWaylineFileInsert.setSpeed(new BigDecimal(speed));
    }

}
